package org.ziegler.javabase.thread.latch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CountDownLatchTest {

    static CountDownLatch countDownLatch = new CountDownLatch(5);

    static ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("countDown. Thread.currentThread().getId() = " + Thread.currentThread().getId());
                countDownLatch.countDown();
            });
        }

        for (int i = 0; i < 2; i++) {
            executorService.submit(() -> {
                System.out.println("before await.Thread.currentThread().getId() = " + Thread.currentThread().getId());
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("after await.Thread.currentThread().getId() = " + Thread.currentThread().getId());
            });
        }

        executorService.shutdown();
        executorService.awaitTermination(1000, TimeUnit.SECONDS);
        System.out.println("CountDownLatchTest.main finished.");
    }


}
